package com.server.thisService.common.convert;

import com.google.gson.reflect.TypeToken;
import com.project.thisCommon.common.CommonFunction;
import com.project.thisCommon.common.ConvertEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.*;
import java.lang.reflect.Type;
import java.util.Map;

public class SpecificationConvert<T> implements Specification<T> {

    T item;

    public SpecificationConvert(T obj){
        item = obj;
    }

    @Override
    public Predicate toPredicate(Root<T> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
        Map<String, Object> cls = ConvertEntity.CovertToMap(item);
        Predicate p = null;
        for (String k : cls.keySet()){
            Object v = cls.get(k);
            if (!CommonFunction.IsNullOrEmptyByObject(v)){
                Path<Object> key_item = root.get(k);
                Predicate next = criteriaBuilder.equal(key_item, v);
                p = null == p ? next : criteriaBuilder.and(p, next);
            }
        }

        return p;
    }
}
